<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" label-position="left" :inline="true" v-show="showSearch"
             label-width="70px">
      <el-form-item label="人员姓名" prop="staffName">
        <el-input
          v-model="queryParams.staffName"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话号码" prop="staffPhonenumber">
        <el-input
          v-model="queryParams.staffPhonenumber"
          placeholder="请输入电话号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="isShowOperate">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['patrol:staff:add']"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['patrol:school:edit']"-->
      <!--        >修改</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['patrol:school:remove']"-->
      <!--        >删除</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          v-hasPermi="['patrol:staff:import']"
        >导入
        </el-button>
      </el-col>
      <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="staffList" style="color: #333333" :header-cell-style="{background:'#E3E3E3'}">
      <el-table-column label="人员姓名" align="center" prop="staffName"/>
      <el-table-column label="身份证号码" align="center" prop="staffIdcard"/>
      <el-table-column label="性别" align="center" prop="staffSex" :formatter="staffSexFormat"/>
      <el-table-column label="职务" align="center" prop="staffPost"/>
      <el-table-column label="电话号码" align="center" prop="staffPhonenumber"/>
      <el-table-column label="所属学校" align="center" prop="schoolName"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="isShowOperate">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['patrol:staff:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['patrol:staff:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改行政人员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="staffName">
              <el-input v-model="form.staffName" placeholder="请输入姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号码" prop="staffIdcard">
              <el-input v-model="form.staffIdcard" placeholder="请输入身份证号码"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="staffSex">
              <el-select v-model="form.staffSex" placeholder="请选择性别">
                <el-option
                  v-for="dict in staffSexOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工龄" prop="staffWorkAge">
              <el-input v-model="form.staffWorkAge" placeholder="请输入工龄"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="籍贯" prop="staffNativePlace">
              <el-cascader
                size="large"
                :options="options"
                v-model="form.staffNativePlace"
                @change="handleChange"
                :key="key"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务" prop="staffPost">
              <el-input v-model="form.staffPost" placeholder="请输入职务"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="电话号码" prop="staffPhonenumber">
              <el-input v-model="form.staffPhonenumber" placeholder="请输入电话号码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="政审情况" prop="staffPoliticalExamine">
              <el-input v-model="form.staffPoliticalExamine" placeholder="请输入政审情况（例如合格或不合格）"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身体状况" prop="staffPhysicalCondition">
              <el-input v-model="form.staffPhysicalCondition" placeholder="请输入身体状况（例如健康或亚健康等）"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="el-upload__tip" style="margin-left: 30px;">
              注意：行政人员添加成功后，只可使用手机登录
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listStaff, delStaff, addStaff, updateStaff, exportStaff, importTemplate} from "@/api/patrol/staff";
import {regionData} from "element-china-area-data";
import {checkPermi} from "@/utils/permission";
import {getToken} from "@/utils/auth"

export default {
  name: "Staff",
  data() {
    let idCard = (rule, value, callback) => {
      if (!value) {
        console.log("111");
        callback();
      } else {
        let _idRe = /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/;
        console.log("222");
        if (!_idRe.test(value)) {
          callback('⾝份证长度或格式错误');
        }
        //⾝份证城市
        var aCity = {
          11: "北京",
          12: "天津",
          13: "河北",
          14: "⼭西",
          15: "内蒙古",
          21: "辽宁",
          22: "吉林",
          23: "⿊龙江",
          31: "上海",
          32: "江苏",
          33: "浙江",
          34: "安徽",
          35: "福建",
          36: "江西",
          37: "⼭东",
          41: "河南",
          42: "湖北",
          43: "湖南",
          44: "⼴东",
          45: "⼴西",
          46: "海南",
          50: "重庆",
          51: "四川",
          52: "贵州",
          53: "云南",
          54: "西藏",
          61: "陕西",
          62: "⽢肃",
          63: "青海",
          64: "宁夏",
          65: "新疆",
          71: "台湾",
          81: "⾹港",
          82: "澳门",
          91: "国外"
        };
        if (!aCity[parseInt(value.substr(0, 2))]) {
          callback('⾝份证长度或格式错误')
        }
        // 出⽣⽇期验证
        var sBirthday = (value.substr(6, 4) + "-" + Number(value.substr(10, 2)) + "-" +
            Number(value.substr(12, 2))).replace(/-/g, "/"),
          d = new Date(sBirthday)
        if (sBirthday != (d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate())) {
          callback('⾝份证长度或格式错误')
        }
        // 出⽣⽇期验证
        var sBirthday = (value.substr(6, 4) + "-" + Number(value.substr(10, 2)) + "-" +
            Number(value.substr(12, 2))).replace(/-/g, "/"),
          d = new Date(sBirthday)
        if (sBirthday != (d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate())) {
          callback('⾝份证长度或格式错误')
        }
        // ⾝份证号码校验
        if (value.length == 18) {
          var sum = 0,
            weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
            codes = "10X98765432"
          for (var i = 0; i < value.length - 1; i++) {
            sum += value[i] * weights[i];
          }
          var last = codes[sum % 11]; //计算出来的最后⼀位⾝份证号码
          if (value[value.length - 1] != last) {
            callback('⾝份证长度或格式错误')
          }
        }
        setFill(value);
        callback();
      }
    }
    let setFill = (value) => {
      let sex = null;
      if (value.length === 18) {
        sex = value.substring(16, 17);
      }
      if (value.length === 15) {
        sex = value.substring(13, 14);
      }
      sex % 2 === 0 ? this.form.staffSex = "1" : this.form.staffSex = "0";
    }
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      options: regionData,
      isStaffIdcardDisabled: false,
      isStaffPhonenumberDisabled: false,
      // 总条数
      total: 0,
      key: 0,
      // 行政人员表格数据
      staffList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 性别字典
      staffSexOptions: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/patrol/staff/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        staffName: null,
        staffIdcard: null,
        staffSex: null,
        staffWorkAge: null,
        staffNativePlace: null,
        staffPost: null,
        staffPhonenumber: null,
        staffPoliticalExamine: null,
        staffPhysicalCondition: null,
        schoolId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        staffName: [
          {required: true, message: "请输入姓名", trigger: "blur"}
        ],
        staffIdcard: [
          // {required: true, message: "请输入身份证号", trigger: "blur"},
          {validator: idCard}
        ],
        staffWorkAge: [
          // {required: true, message: "请输入工龄", trigger: "blur"},
          {min: 1, max: 3, message: "工龄长度需满足1-3位", trigger: "change"},
          // {required: true, message: "请输入工龄", trigger: "blur"},
          {min: 1, max: 3, message: "工龄长度需满足1-3位", trigger: "change"},
        ],
        // staffNativePlace: [
        // {required: true, message: "请输入籍贯", trigger: "blur"}
        // ],
        staffPost: [
          {required: true, message: "请输入职位", trigger: "blur"},
          {min: 1, max: 30, message: "职位长度需满足1-30位", trigger: "change"}
        ],
        staffPhonenumber: [
          {required: true, message: "请输入电话", trigger: "blur"},
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "change"
          }
        ],
        staffPoliticalExamine: [
          {required: true, message: "请输入政审情况", trigger: "blur"},
          {min: 1, max: 30, message: "政审情况长度需满足1-30位", trigger: "change"}
        ],
        staffPhysicalCondition: [
          {required: true, message: "请输入身体状况", trigger: "blur"},
          {min: 1, max: 30, message: "身体状况长度需满足1-30位", trigger: "change"}
        ],
      }
    };
  },
  computed: {
    isShowOperate: function () {
      return checkPermi(['patrol:staff:edit']);
    },
  },
  created() {
    this.queryParams.schoolId = this.$route.query.schoolId;
    this.getList();
    this.getDicts("sys_user_sex").then(response => {
      this.staffSexOptions = response.data;
    });
  },
  methods: {
    /** 查询行政人员列表 */
    getList() {
      this.loading = true;
      listStaff(this.queryParams).then(response => {
        this.staffList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 性别字典翻译
    staffSexFormat(row, column) {
      return this.selectDictLabel(this.staffSexOptions, row.staffSex);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        staffName: null,
        staffIdcard: null,
        staffSex: null,
        staffWorkAge: null,
        staffNativePlace: null,
        staffPost: null,
        staffPhonenumber: null,
        staffPoliticalExamine: null,
        staffPhysicalCondition: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null,
        schoolId: null
      };
      this.resetForm("form");
      this.key++;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加行政人员";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      if (!Array.isArray(row.staffNativePlace) && row.staffNativePlace) {
        row.staffNativePlace = row.staffNativePlace.split(",");
      }
      if (row.staffWorkAge) {
        row.staffWorkAge = row.staffWorkAge.toString();
      }
      this.form = {...row};
      this.open = true;
      this.title = "修改行政人员";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            if (this.form.staffNativePlace) {
              this.form.staffNativePlace = this.form.staffNativePlace.toString();
            }
            updateStaff(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStaff(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.resetQuery();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除所选数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning"
      }).then(function () {
        return delStaff(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    handleChange(value) {
      console.log(value, value.toString());
      this.form.staffNativePlace = value.toString();
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有行政人员数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning"
      }).then(function () {
        return exportStaff(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "行政人员导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
